export default {
  set(key, value) {
    try {
      uni.setStorageSync(key, JSON.stringify(value));
      return true;
    } catch (error) {
      console.error(`存储数据 ${key} 时出错:`, error);
      return false;
    }
  },

  get(key, defaultValue = null) {
    try {
      const value = uni.getStorageSync(key);
      if (value === "" || value === null || value === undefined) {
        return defaultValue;
      }
      return JSON.parse(value);
    } catch (error) {
      console.error(`读取存储数据 ${key} 时出错:`, error);
      return defaultValue;
    }
  },

  async setAsync(key, value) {
    try {
      await uni.setStorage({ key, data: JSON.stringify(value) });
      return true;
    } catch (error) {
      console.error(`异步存储数据 ${key} 时出错:`, error);
      return false;
    }
  },

  async getAsync(key, defaultValue = null) {
    try {
      const res = await uni.getStorage({ key });
      if (!res || !res[1] || !res[1].data) {
        return defaultValue;
      }
      return JSON.parse(res[1].data);
    } catch (error) {
      console.error(`异步读取存储数据 ${key} 时出错:`, error);
      return defaultValue;
    }
  },

  remove(key) {
    try {
      uni.removeStorageSync(key);
      return true;
    } catch (error) {
      console.error(`删除存储数据 ${key} 时出错:`, error);
      return false;
    }
  },

  async removeAsync(key) {
    try {
      await uni.removeStorage({ key });
      return true;
    } catch (error) {
      console.error(`异步删除存储数据 ${key} 时出错:`, error);
      return false;
    }
  },

  clear() {
    try {
      uni.clearStorageSync();
      return true;
    } catch (error) {
      console.error("清空存储时出错:", error);
      return false;
    }
  },

  async clearAsync() {
    try {
      await uni.clearStorage();
      return true;
    } catch (error) {
      console.error("异步清空存储时出错:", error);
      return false;
    }
  },

  has(key) {
    try {
      const value = uni.getStorageSync(key);
      return value !== "" && value !== null && value !== undefined;
    } catch (error) {
      console.error(`检查存储键 ${key} 是否存在时出错:`, error);
      return false;
    }
  },

  getInfo() {
    try {
      const info = uni.getStorageInfoSync();
      return {
        keys: info.keys || [],
        currentSize: info.currentSize || 0,
        limitSize: info.limitSize || 0,
      };
    } catch (error) {
      console.error("获取存储信息时出错:", error);
      return { keys: [], currentSize: 0, limitSize: 0 };
    }
  },

  setMultiple(obj) {
    try {
      Object.keys(obj).forEach((key) => {
        this.set(key, obj[key]);
      });
      return true;
    } catch (error) {
      console.error("批量存储数据时出错:", error);
      return false;
    }
  },

  getMultiple(keys) {
    try {
      const result = {};
      keys.forEach((key) => {
        result[key] = this.get(key);
      });
      return result;
    } catch (error) {
      console.error("批量读取存储数据时出错:", error);
      return {};
    }
  },
};
